layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	var index_name = sessionStorage.getItem("userInfo");
	var f = JSON.parse(index_name)
	if(f==null||f==""){
		window.location.href = "../login/login.html";
	}

	/*//设置跨域请求
	app.all('*', function (req, res, next) {
		res.header("Access-Control-Allow-Origin", "*");
		res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
		res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
		res.header("X-Powered-By", ' 3.2.1')
		res.header("Content-Type", "application/json;charset=utf-8");
		next();
	});*/




	//加载页面数据
	var usersData = {};
	$.get("http://localhost:8080/com.3group.personality/user/selectWebUser", function(data){
		console.log("123")
		usersData = data;
		/*if(window.sessionStorage.getItem("addUser")){
			var addUser = window.sessionStorage.getItem("addUser");
			usersData = JSON.parse(addUser).concat(usersData);

		}*/

		usersData=JSON.parse(data);
		//执行加载数据的方法
		usersList(JSON.parse(data));
	})

	//查询
	$(".search_btn").click(function(){
		var userArray = [];
		if($(".search_input").val() != ''){
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
			setTimeout(function(){
				$.ajax({
					url : "http://localhost:8080/com.3group.personality/user/selectWebUser",
					type : "post",
					dataType : "json",
					success : function(data){

						if(window.sessionStorage.getItem("addUser")){
							var addUser = window.sessionStorage.getItem("addUser");
							usersData = JSON.parse(addUser).concat(data);
						}else{
							usersData = data;
						}
						console.log("查询为："+usersData)
						for(var i=0;i<usersData.length;i++){
							var usersStr = usersData[i];
							var selectStr = $(".search_input").val();
							function changeStr(data){
								var dataStr = '';
								var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
								if(showNum > 1){
									for (var j=0;j<showNum;j++) {
										dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
									}
									dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
									return dataStr;
								}else{
									dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
									return dataStr;
								}
							}
							//用户id
							if(usersStr.userid.indexOf(selectStr) > -1){
								usersStr["userid"] = changeStr(usersStr.userid);
							}
							//昵称
							if(usersStr.name.indexOf(selectStr) > -1){
								usersStr["name"] = changeStr(usersStr.name);
							}
							//性别
							if(usersStr.sex.indexOf(selectStr) > -1){
								usersStr["sex"] = changeStr(usersStr.sex);
							}
							/*//介绍
							if(usersStr.introduction.indexOf(selectStr) > -1){
								usersStr["introduction"] = changeStr(usersStr.introduction);
							}*/
							if(usersStr.userid.indexOf(selectStr)>-1 || usersStr.name.indexOf(selectStr)>-1 || usersStr.sex.indexOf(selectStr)>-1){
								userArray.push(usersStr);
							}
						}
						usersData = userArray;
						usersList(usersData);
					}
				})

				layer.close(index);
			},2000);
		}else{
			layer.msg("请输入需要查询的内容");
		}
	})

	/*//添加会员
	$(".usersAdd_btn").click(function(){
		var index = layui.layer.open({
			title : "添加会员",
			type : 2,
			content : "addUser.html",
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回会员列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})*/

	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.users_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.users_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
				setTimeout(function(){
					//删除数据
					for(var j=0;j<$checked.length;j++){
						for(var i=0;i<usersData.length;i++){
							if(usersData[i].userid == $checked.eq(j).parents("tr").find(".users_del").attr("data-id")){
								console.log("批量删除："+usersData[i].userid)
								$.ajax({
									url: "http://localhost:8080/com.3group.personality/user/delete?id=" +usersData[i].userid,
									type: "post",
									dataType: "json",
									success: function (date) {
										console.log(data);
										alert("删除成功")
										usersData.splice(i, 1);
										usersList(date)
										window.location.href = 'allUsers.html'
									}
								})
								usersData.splice(i,1);
								usersList(usersData);
							}
						}
					}
					$('.users_list thead input[type="checkbox"]').prop("checked",false);
					form.render();
					layer.close(index);
					layer.msg("删除成功");
				},2000);
			})
		}else{
			layer.msg("请选择需要删除的用户");
		}
	})

	//全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	/*//操作
	$("body").on("click",".users_edit",function(){  //编辑
		layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});
	})*/

	$("body").on("click",".users_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
			//_this.parents("tr").remove();
			console.log("获取到的值为："+usersData)
			console.log("获取到的条数为："+usersData.length)
			for(var i=0;i<usersData.length;i++){
				// console.log("输出1："+usersData[i].userid)
				// console.log("输出2："+_this.attr("data-id"))
				if(usersData[i].userid == _this.attr("data-id")){
					console.log("删除2")
					$.ajax({
						url: "http://localhost:8080/com.3group.personality/user/delete?id=" + _this.attr("data-id"),
						type: "post",
						dataType: "json",
						success: function (date) {
							console.log("返回值为"+data);
							alert("删除成功")
							usersData.splice(i, 1);
							usersList(date)
							window.location.href = "allUsers.html"
						}
					})
					usersData.splice(i,1);
					usersList(usersData);
				}
			}
			layer.msg("删除成功");
			layer.close(index);
		});
	})

	function usersList(that){
		//渲染数据
		function renderDate(data,curr){
			// console.log("获取到的值为："+data)
			var dataHtml = '';
			if (!that){
				currData = usersData.concat().splice(curr*nums-nums, nums);
			}else {
				currData = that.concat().splice(curr*nums-nums, nums);
			}

			if(currData.length != 0){
				for(var i=0;i<currData.length;i++){

					dataHtml += '<tr>'
						+  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
						+  '<td>'+currData[i].userid+'</td>'
						+  '<td>'+currData[i].name+'</td>'
						+  '<td>'+currData[i].sex+'</td>'
						+  '<td>'+currData[i].phone+'</td>'
						+  '<td>'+currData[i].introduction+'</td>'
						/*+  '<td>'+currData[i].userEndTime+'</td>'*/
						+  '<td>'
						/*+    '<a class="layui-btn layui-btn-mini users_edit"><i class="iconfont icon-edit"></i> 编辑</a>'*/
						+    '<a class="layui-btn layui-btn-danger layui-btn-mini users_del" data-id="'+data[i].userid+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
						+  '</td>'
						+'</tr>';
					// console.log("userid值为："+data[i].userid)
				}
			}else{
				dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
			}
			return dataHtml;
		}

		//分页
		var nums = 13; //每页出现的数据量
		laypage({
			cont : "page",
			pages : Math.ceil(usersData.length/nums),
			jump : function(obj){
				$(".users_content").html(renderDate(usersData,obj.curr));
				$('.users_list thead input[type="checkbox"]').prop("checked",false);
				form.render();
			}
		})
	}

})